<template>
  <div id="configs">
    <div class="search-context">
      <el-input
        v-model="paInputVal"
        size="small"
        class="search-input-class"
        placeholder="配置项Key/名称/值/描述"
        clearable
      />
      <el-button type="primary" size="small" @click="search">查询</el-button>
      <el-button
        style="margin-left: auto"
        size="small"
        type="primary"
        @click="editConfig(1, undefined)"
      >
        <i class="el-icon-plus" />
        新增
      </el-button>
    </div>
    <el-divider />
    <el-table
      id="cfg-table"
      :data="configData"
      row-key="id"
      border
      max-height="700px"
      style="width: 100%"
      header-cell-class-name="cfg-header-cell"
      :cell-class-name="setCellClassName"
      :row-class-name="rowClassName"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @expand-change="showRowAll"
    >
      <el-table-column
        v-for="cfgHeader in configHeaders"
        :key="cfgHeader.prop"
        :prop="cfgHeader.prop"
        :label="cfgHeader.label"
        :width="cfgHeader.width"
      >
        <template slot-scope="scope">
          <div v-if="cfgHeader.isOp">
            <el-button type="text" size="mini" @click="editConfig($const.OPERATE_TYPE_ADD, scope.row)">
              <i class="el-icon-plus" />新增
            </el-button>
            <el-button type="text" size="mini" @click="editConfig($const.OPERATE_TYPE_EDIT, scope.row)">
              <i class="el-icon-edit" /> 修改
            </el-button>
            <el-button type="text" size="mini" @click="editConfig($const.OPERATE_TYPE_OFFLINE, scope.row)">
              <i :class="scope.row['status'] === $const.STATUS_ONLINE ? 'el-icon-bottom' : 'el-icon-top'" />
              {{ scope.row['status'] === $const.STATUS_ONLINE ? '下线' : '上线' }}
            </el-button>
            <el-popover
              v-model="scope.row['showDelete']"
              placement="top"
              width="160"
              style="margin-left: 10px"
            >
              <p>确定删除码？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="scope.row['showDelete'] = false">取消</el-button>
                <el-button type="primary" size="mini" @click="editConfig($const.OPERATE_TYPE_DELETE, scope.row)">确定</el-button>
              </div>
              <el-button
                ref="popoverBtn"
                slot="reference"
                type="text"
                size="mini"
                :click-id="scope.row.id"
              >
                <i class="el-icon-delete" /> 删除
              </el-button>
            </el-popover>
          </div>
          <div v-else-if="cfgHeader.prop === 'isDefault_s'">
            <el-badge
              v-if="scope.row[cfgHeader.prop] === '是'"
              :value="'默认'"
              class="item"
              type="primary"
            >
              <el-tag type="info" size="small"> {{ scope.row[cfgHeader.prop] }} </el-tag>
            </el-badge>
            <span v-else>{{ scope.row[cfgHeader.prop] }}</span>
          </div>
          <span v-else>{{ scope.row[cfgHeader.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-draggable
      :title="dialogTitle"
      :visible.sync="configVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <ConfigEdit
        :config-info="editInfo"
        :operate-type="operateType"
        @cancel-edit="cancelEdit"
        @submit-edit="submitEdit"
      />
    </el-dialog>
  </div>
</template>
<script>
import { constants as $const } from '@/store/constants'
import { querySystemConfigs, updateSystemConfig } from '@/api/config'
import ConfigEdit from '@/views/systemSetting/configs/ConfigEdit.vue'

export default {
  name: 'Configs',
  components: { ConfigEdit },
  data() {
    return {
      paInputVal: '',
      dialogTitle: '新增配置项',
      configVisible: false,
      confirmVisible: false,
      configHeaders: [{
        label: '配置项KEY',
        prop: 'configKey'
      }, {
        label: '配置项名称',
        prop: 'configName'
      }, {
        label: '别名',
        prop: 'alias'
      }, {
        label: '配置项值',
        prop: 'configValue'
      }, {
        label: '配置项描述',
        prop: 'configDesc'
      }, {
        label: '是否启用',
        prop: 'isAlive_s',
        width: '100px',
        isFilter: true
      }, {
        label: '是否默认',
        prop: 'isDefault_s',
        isFilter: true,
        width: '100px'
      }, {
        label: '操作',
        prop: 'operator',
        isOp: true,
        width: '230px'
      }],

      configData: [],
      editInfo: {},
      operateType: $const.OPERATE_TYPE_ADD,
      opStatus: $const.STATUS_OFFLINE,
      beforeExpanded: {} // 刷新数据之前的每行展开状态
    }
  },
  computed: {
    $const() {
      return $const
    }
  },
  created() {
    this.initData()
  },
  methods: {
    rowClassName({ row, rowIndex }) {
      if (row.status === 0) {
        return 'offline-row'
      }

      if (!row.expanded) {
        return ''
      }
      return 'success-row'
    },

    setCellClassName({ row, column, rowIndex, columnIndex }) {
      const property = column.property
      if (property === 'configKey') {
        return ''
      }
      return 'cfg-data-cell'
    },

    showRowAll(row, expanded) {
      row['expanded'] = expanded
      const subRows = row.children
      if (subRows && subRows.length > 0) {
        subRows.forEach(item => { item['expanded'] = expanded })
      }
    },

    initData() {
      this.paInputVal = ''
      this.search()
    },

    // 搜索操作
    search() {
      querySystemConfigs({ searchValue: this.paInputVal }).then(res => {
        this.configData = res.data
        this.configData.forEach(item => {
          item['isAlive_s'] = item.status === 1 ? '是' : '否'
          item['isDefault_s'] = item.isDefault === 1 ? '是' : '否'
          const subItems = item.children
          if (subItems && subItems.length > 0) {
            const isExpand = this.beforeExpanded[item.id]
            item['expanded'] = isExpand
            subItems.forEach(subItem => {
              subItem['isAlive_s'] = subItem.status === 1 ? '是' : '否'
              subItem['isDefault_s'] = subItem.isDefault === 1 ? '是' : '否'
              subItem['expanded'] = isExpand
            })
          }
        })
      }).catch(err => {
        console.error(err)
        this.$message.error('！！初始化系统配置数据失败！！')
      })
    },

    // 增加配置操作
    editConfig(operateType, row) {
      this.recordExpanded(row)

      // 下线操作
      if (operateType === this.$const.OPERATE_TYPE_OFFLINE) {
        const reqConfig = { ...row }
        reqConfig['status'] = row.status === this.$const.STATUS_OFFLINE ? this.$const.STATUS_ONLINE : this.$const.STATUS_OFFLINE
        reqConfig['operateType'] = this.$const.OPERATE_TYPE_EDIT
        updateSystemConfig(reqConfig).then(res => {
          this.$message.success('操作成功')
          this.initData()
        }).catch(err => {
          console.error(err)
          this.$message.error('！！操作失败！！')
        })
        return
      }

      // 删除操作
      if (operateType === this.$const.OPERATE_TYPE_DELETE) {
        this.confirmVisible = false
        const reqConfig = { ...row }
        reqConfig['operateType'] = this.$const.OPERATE_TYPE_DELETE
        updateSystemConfig(reqConfig).then(res => {
          this.$message.success('操作成功')
          this.initData()
        }).catch(err => {
          console.error(err)
          this.$message.error('！！操作失败！！')
        })
        return
      }

      // 新增和编辑
      this.configVisible = true
      if (operateType === this.$const.OPERATE_TYPE_ADD) {
        this.dialogTitle = '新增配置项'
        this.editInfo = !row ? { isEdit: true } : {
          id: row.id,
          configKey: row.configKey,
          configName: row.configName,
          isEdit: false
        }
        this.operateType = this.$const.OPERATE_TYPE_ADD
      } else {
        this.dialogTitle = '编辑配置项'
        this.editInfo = { ...row, isEdit: false }
        this.operateType = this.$const.OPERATE_TYPE_EDIT
      }
    },

    recordExpanded(row) {
      const rowId = row.id
      this.configData.forEach(item => {
        if (item.id === rowId) {
          // 记录展开状态
          this.beforeExpanded[rowId] = row.expanded
          return
        }
        const subItems = item.children
        if (subItems && subItems.length > 0) {
          subItems.forEach(subItem => {
            if (subItem.id === rowId) {
              // 只需要记录父级节点的ID
              this.beforeExpanded[item.id] = row.expanded
            }
          })
        }
      })
    },

    cancelEdit() {
      this.configVisible = false
      this.initData()
    },

    submitEdit() {
      this.configVisible = false
      this.initData()
    }
  }
}
</script>
<style scoped>
#configs {
  margin: 30px;
}

.search-context {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
}

.search-input-class{
  width: 300px;
  flex: 0 1 auto; /* 禁止扩展和收缩 */
  min-width: 0; /* 防止内容溢出（关键） */
}

#cfg-table /deep/ .success-row {
  background: #FDF5E6;
  color: #001528;
}

/deep/ .el-table__row .cell {
  transition: all 0.3s ease;
}

#cfg-table /deep/ .offline-row {
  color: #999999;
  background: #E5E4EB;
}

.item {
  margin-top: 10px;
  margin-right: 20px;
}

#cfg-table /deep/ .cfg-header-cell {
  background-color: #E5E4EB;
  text-align: center;
}

#cfg-table /deep/ .cfg-data-cell {
  text-align: center;
}

</style>
